<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var GLOBAL = {
    CONTEXT_PATH : "http://u.im-cc.com:80/"
};
</script>
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<link rel="icon" href="http://u.im-cc.com/favicon.ico">
<link rel="stylesheet" href="./gzt_files/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="./gzt_files/font-awesome.min.css">
<link rel="stylesheet" href="./gzt_files/pnotify.css">
<link rel="stylesheet" href="./gzt_files/pnotify.buttons.css">
<link rel="stylesheet" href="./gzt_files/webuploader.css">
<link href="./gzt_files/font.css" rel="stylesheet">
<script src="./gzt_files/jQuery-2.1.4.min.js.下载"></script>
<script src="./gzt_files/jquery-migrate-1.2.1.js.下载"></script>
<script src="./gzt_files/bootstrap.min.js.下载"></script>
<script src="./gzt_files/common.js.下载"></script>
<title>云软云客服</title>
<script type="text/javascript">
	var isToLoad = "";
	function phone(ani,cType,dict){
		Ani= ani;
		callType = cType;
		phoneHref();
		if(isToLoad=="true"){
			if(window.mainFrame.nowChatShow){
				window.mainFrame.nowChatShow(ani,cType,dict);
			}
		}
	}
	
	function uboxPhone(ani,cType,dict){
		Ani= ani;
		phoneHref();
		if(window.mainFrame.nowChatShow){
			window.mainFrame.nowChatShow(ani,cType,dict);
		}
	}
	
	function hangPhone(){
		closeHint();//隐藏电话按钮提示
// 		Ani= "";
// 		callType = "";
// 		phoneHref();//重置超链接
		if(isToLoad=="true"){
			if(window.mainFrame.nowChatHide){
				window.mainFrame.nowChatHide();
			}
		}
		if(isPhoneChange==true){//如果是通话自动示忙，通话结束后切换回在线状态
			switchStatus('1');
		}
	}
	
	function closeHint(){
		$('.icon-phone-square').removeClass("tada");
	}
	
	//打开来话原因抽屉
	function treeReasonOpen(ani, nopop){
		if(window.mainFrame.treeReasonOpen){
			window.mainFrame.treeReasonOpen(ani, nopop);
		}
	}
	
	//电话外拨接口     
	function callOut(phoneNum){
		window.opener.callOut(phoneNum);
	}

	//定时检查用户是否退出浏览器
	window.setInterval(checkOnline,60000); 
	function checkOnline() {
		var url = '/intervalCheck.do?randomNum='+ Math.random()*1000;
		$.ajax({
	        async : true,
	        type : 'GET',
	        url : url,
	        error: function (){
            },
            complete: function(){}
	    });
	}
	
	//更新会话记录接口
	function updateRecord(){
		if(window.mainFrame.findHistory){
			window.mainFrame.findHistory('1');
		}
	}
</script><link rel="stylesheet" href="./gzt_files/layer.css" id="layui_layer_skinlayercss" style=""></head>
<body class="x-body x-webkit x-chrome x-reset" id="ext-gen1018">
<script type="text/javascript" src="./gzt_files/ext-all.js.下载"></script>
<script type="text/javascript" src="./gzt_files/ext-lang-zh_CN.js.下载"></script>
<script type="text/javascript" src="./gzt_files/jquery.timers.js.下载"></script>
<script type="text/javascript" src="./gzt_files/AgentUI.js.下载"></script>
<script type="text/javascript" src="./gzt_files/AgentProxy.js.下载"></script>
<script type="text/javascript" src="./gzt_files/AgentStateInterpretor.js.下载"></script>
<script type="text/javascript" src="./gzt_files/require.config.js.下载"></script>
<link rel="shortcut icon" href="./gzt_files/service.png" type="image/png">
<link rel="stylesheet" href="./gzt_files/bootstrap.min.css">
<link rel="stylesheet" href="./gzt_files/app.css">
<link href="./gzt_files/font.css" rel="stylesheet">
<script src="./gzt_files/pnotify.js.下载"></script>
<script src="./gzt_files/pnotify.buttons.js.下载"></script>
<script src="./gzt_files/imcc_plugin.js.下载"></script>
<nav class="navbar navbar-fixed-top ucc-header">
<common:csrftoken>
<audio id="tipsAudio" src="/static/assets/img/tips.mp3"></audio>
    <div class="container-fluid">
      <div class="navbar-header">
        <a class="navbar-brand" href="javascript:;">
              <img src="./gzt_files/up_logo_white.png" alt="企业logo" title="企业logo">
        </a>
      </div>
      <div id="navbar">
        <ul class="nav navbar-nav navbar-right">
          <li>
          	<a class="withoutripple call">
<!--           		<button class="" onclick="test()">点击测试</button> -->
           		<button class="icon-dianhua btn" style="display:none;" id="callup" name="OnCallup" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="拨号">电话正常图标</button>
          		<button class="icon-guaduan btn" style="display:none;">电话来电图标</button>
              	<button class="icon-laidian btn" style="display:none;" id="Hook" name="OnHook" onclick="btn(this)" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="摘机">摘机</button>
          	</a>
          </li>
          <li id="newNote" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="消息通知">
            <a href="javascript:;" class="withoutripple notice new">
              <i class="icon icon-bell"></i>
            </a>
          </li>
          <li class="sidemenu zt" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="头像">
            <a href="javascript:;" class="withoutripple photo">
                  
				   
				   		<img id="personalImg" src="./gzt_files/service.png" alt="头像"><i class="zt" style="background: url(&quot;/static/assets/img/online.png&quot;) center center no-repeat;"></i>
				   	  
				   	  
			    
			</a>
          </li>
          <li class="sidemenu" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="个人信息">
            <a href="javascript:;" class="withoutripple names"><span id="userName">潘先生</span><br><span id="userType">客服代表</span></a>
          </li>
        </ul>
        <!-- 拨打电话功能栏 -->
        <div class="callup-functions">
          <!-- 状态文本显示区域 -->
          <div class="callup-text">
          	 <span id="txtAni"></span>
          	 <span id="state" style="display:none;">未登录状态</span>
          	 <span id="Time"></span>
          </div>
          <!-- 通话中 -->
          <div class="callup-calling">
          	<ul class="nav navbar-nav">
           		<li>
             		<button class="btn btn-turn" style="display:none;" id="Transfer" name="Transfer" onclick="btn(this)" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="转接">转接</button>
             	</li>
	            <li>
		            <button class="btn btn-start" style="display:none;" id="Hold" name="Hold" onclick="btn(this)" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="保持">保持</button>
	            </li>
	            <li>
	              <button class="btn btn-mark" style="display:none;" id="ServiceLevel" name="ServiceLevel" onclick="btn(this)" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="满意度">满意度</button>
	            </li>
	      	</ul>
          </div>
        </div>
      </div>
       <!-- 拨打电话popover -->
      <div class="callup-tpl popover-tpl">
        <div class="callup-container">
          <ul class="list">
            <li class="list-item">拨打电话 
<!--               <button class="btn btn-huatong btn-sm fr">话筒</button> -->
              <button class="btn btn-success btn-sm fr" id="online">在线</button>
            </li>
            <li class="list-item">本机号码：</li>
          </ul>
          <section class="jianpan">
            <div class="input">
              <input type="text" id="DnisText" class="val" onkeyup="this.value=this.value.replace(/[^\r\n0-9]/g,&#39;&#39;);">
              <button class="btn btn-del"></button>
            </div>
            <dl class="numbers">
              <dd class="number">1</dd>
              <dd class="number">2</dd>
              <dd class="number">3</dd>
              <dd class="number">4</dd>
              <dd class="number">5</dd>
              <dd class="number">6</dd>
              <dd class="number">7</dd>
              <dd class="number">8</dd>
              <dd class="number">9</dd>
              <dd class="number m">*</dd>
              <dd class="number">0</dd>
              <dd class="number">#</dd>
            </dl>
            <button class="btn btn-block btn-send" id="DialOut" name="DialOut" onclick="btn(this)" title="呼叫">外拨</button>
            <button class="btn btn-block btn-over" id="overCall" onclick="btn(this)" style="margin:0" title="挂断">挂机</button>
          </section>
        </div>
      </div>
      <!-- 转接popover -->
      <div class="pass-tpl popover-tpl">
        <div class="pass-container" role="tabpanel">
          <!-- Nav tabs -->
          <ul class="nav nav-tabs" role="tablist" id="phone">
            <li role="presentation" class="active" onclick="isInside(true)"><a href="http://u.im-cc.com/login/main.do#passInner" aria-controls="passInner" role="tab" data-toggle="tab">转内线</a></li>
            <li role="presentation" onclick="isInside(false)"><a href="http://u.im-cc.com/login/main.do#passOutter" aria-controls="passOutter" role="tab" data-toggle="tab">转外线</a></li>
          </ul>
          <!-- Tab panes -->
          <div class="tab-content">
            <!-- 转内线panel -->
            <div role="tabpanel" class="tab-pane fade in active" id="passInner">
              <ul id="agentDiv" class="kefu-list">
              </ul>
            </div>
            <!-- 转外线panel -->
            <div role="tabpanel" class="tab-pane fade" id="passOutter">
              <label class="label">输入外线号码</label>
              <textarea onkeyup="this.value=this.value.replace(/[^\r\n0-9]/g,&#39;&#39;);" name="" id="newAni" class="textarea" rows="3"></textarea>
            </div>
          </div>
          <button class="btn btn-success fl" onclick="selectOK()">转接</button>
          <button class="btn btn-primary fr" id="passChatCancel" onclick="passChatCancel()">取消</button>
        </div>
      </div>
      <div class="newnote-tpl popover-tpl">
      <div class="newnote-container" role="tabpanel">
        <!-- Tab panes -->
        <div class="tab-content">
          <!-- 查看消息panel -->
          <dl class="list-group" id="laterNews">
          </dl>
          <dl class="list-group" id="workOrders">
          </dl>
           <dl class="list-group" id="ProcessingNotice">
          </dl>
          <p style="padding-top:5px;text-align:center;width:100%;" class="noMsg">没有未读的消息</p>
          <div class="footer-btns" style="display:none" id="readbtn">
            <button class=" btn--success btn-sm readAll" style="width:46%">全部已读</button>
            <!-- <button class="btn btn--success btn-sm" style="width:46%" id="toMore">查看更多消息</button> -->
          </div>
        </div>
      </div>
    </div>
      <!-- 在线状态popover -->
      <div class="online-tpl popover-tpl">
        <div class="online-container">
          <ul class="list-group">
            <li class="list-group-item on"><a class="" id="Pause" data-bgcolor="#3BCD82" onclick="btn(this)">在线</a></li>
            <li class="list-group-item busy">
            	<a class="" id="Busy" data-bgcolor="#F88B50" onclick="btn(this)">示忙</a>
            	<ul class="menulist" id="pauseDiv"></ul>
            </li>
<!--             <li class="list-group-item off"><a class="" data-bgcolor="#616974" onclick="DialOutClick('01')">外拨</a></li> -->
          </ul>
        </div>
      </div>
      <!-- 客服信息修改侧边栏 -->
      <div class="sm-container" id="logOut">
        <div class="sm-mask"></div>
        <div class="sm-content">
         <div class="btn-group" style="width:100%;position: relative;">
	            <select class="se" id="onlineSel" onchange="switchStatus()">
	              <option value="1" selected="">在线</option>
	              <option value="3">示忙</option>
	              <option value="5">离线</option>
	            </select>
	            
        </div>
        
          <ul class="list-group">
            <li class="list-group-item" onclick="chooseFirstMenu(&#39;设置&#39;, true);return $(&#39;.sm-mask&#39;).click();">个人信息</li>
            
                <li class="list-group-item" onclick="toWorkerCount()">个人工作统计</li>
            
            <li class="list-group-item" onclick="toNoviceGuide()">新手向导</li>
<!--             <li class="list-group-item">反馈和建议</li> -->
          </ul>
          <ul class="list-group">
            <li class="list-group-item">
              接入量设置
              <div class="input-group input-amount">
                  <div class="input-group-addon" onclick="addOrSubtractConnCount(&#39;subtract&#39;)">-</div>
                  <div class="form-group"><input type="text" class="form-control" id="defaultConnCount" value="5" readonly=""><span class="material-input"></span></div>
                  <div class="input-group-addon" onclick="addOrSubtractConnCount(&#39;add&#39;)">+</div>
              </div>
            </li>
            </ul>
          <ul class="list-group tuichu">
            <li class="list-group-item tac" data-toggle="modal" data-target="#tcdl"><a href="javascript:void(0)">退出登录 <img src="./gzt_files/icon_tuichu.png" alt=""></a></li>
          </ul>
        </div>
      </div>
      
    </div>
  </common:csrftoken></nav>
  <!-- 公司公告模态框 -->
<div class="modal fade modal-confirm" id="modalNotice">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h4 class="modal-title">温馨提示</h4>
            </div>
            <div class="modal-body">
                是否确认要跳转公司公告页面？
            </div>
            <div class="modal-footer" style="text-align:center">
                <button type="button" class="btn btn-success" id="toCompany">确认</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>
<!-- 工单提醒模态框 -->
<div class="modal fade modal-confirm" id="modalOrder">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h4 class="modal-title">温馨提示</h4>
            </div>
            <div class="modal-body">
                是否确认要跳转我处理中的工单页面？
            </div>
            <div class="modal-footer" style="text-align:center">
                <button type="button" class="btn btn-success" id="toOrder">确认</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade modal-confirm" id="modalSystem">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h4 class="modal-title">温馨提示</h4>
            </div>
            <div class="modal-body">
                是否确认要跳转我发起的工单页面？
            </div>
            <div class="modal-footer" style="text-align:center">
                <button type="button" class="btn btn-success" id="toOrderstatus">确认</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>
  <!--退出登录模态框--->
  <div class="modal fade modal-confirm" id="tcdl">
    <div class="modal-dialog modal-sm">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
          <h4 class="modal-title">退出</h4>
        </div>
        <div class="modal-body">
          是否确认要退出登录？
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-success fl" data-dismiss="modal" onclick="signout();return false;">确认退出</button>
          <button type="button" class="btn btn-default fr" data-dismiss="modal">取消</button>
        </div>
      </div>
    </div>
  </div>
<script type="text/javascript">
var category = true;
var agProxy = new AgentProxy();
var agentId;//转接坐席ID
var Ani = "";//超链接参数	
var AniTwo = "";//整合会话记录参数
var isCallOver = false;//外拨状态
var stateText = "";//状态
var stateColour = "";//状态背景颜色
var callType = "";//呼叫类型 0 呼入 1 外拨
var convTimer;    //会话定时器
var dialOutNum = "";//外拨号码
var isPhoneChange =  false;//是否外拨时自动切换状态
var callupPrefix = "";//电话呼叫前缀
var v_ani = '';//外呼主叫号码
var taskCustomerId="";

$(document).ready(function() {
	//如果该客服允许电话接入就登陆电话客服
	if(''=="Y"){
		if('' == "1"){//判断电话接入类型：1 SIP 2 USB
			$("#state").show();
			callupPrefix = '';
			this.SipIP = '';//该客服话机IP地址
			if('false' =="true")//是否强制登录
			{
				setTimeout(
					function () {
						OnLoginClickIMCC('','','','','','','');
					},
				5000);
			}
			else
			{
				OnLoginClickIMCC('','','','','','','');
			}
		}else{
			//获取USB插件端口，建立webSocket连接
			$.ajax({
		        url: "http://127.0.0.1:9904", 
		        type: "GET",
		        data: {"phone":"start"},
		        dataType: "jsonp",
		        jsonp: "callback",
		        jsonpCallback:"jsonpCallback",
		        success: function(data){
		        	//setTimeout(function(){},'5000');
// 		        	alert(data.port);
					foundWebSocket(data.port);
		        },
		        error : function(data){
		            notify("提示", "启动失败", "fail", 2000);
		        }
		    });
		}
	}
	
	var titleTimer;
	var title = document.title;
	var count = 0;
	var msgCount=0;
	var tooltipid = '115781000';
	//客服拉取会话协议
	function convlist() {
		if($("#mainFrame").attr("src").indexOf("/chat_v4/") >= 0){
			document.title = title;
			if(titleTimer) {
				clearInterval(titleTimer);
				titleTimer = null;
			}
			$("#chatcorner").css("display", "none");
		} else {
			var url ="http://u.im-cc.com:7081";
			var msgid=getMsgId(32);
	         //var url = self.baseUrl + "chat/convlist.do";
			var headers = {};
			$.ajax({
				type: 'post', 
		        url: url, 
		        timeout : 5000, //超时时间设置，单位毫秒
		        data:'{"command":"0x32","systemid":"11578","loginuserid":"28504","convtype":"0","msgid":"'+msgid+'"}',
		        dataType:"json",
		        async: true, 
		        success: function(data){
		        	//console.log(data);
		        	if(!data){return;}
		        	//var obj = JSON.parse(data); // eval("(" + data + ")");
		        	if(data.code==0){
                   	//console.log(data.session_list.count);
                   		syncStatus(data.session_list.clientstatus);
                       if(data.session_list && data.session_list.count>0 && data.loginuserid=="28504"){
                       	var unread = 0;
                       	var hasNewConv = false;
                           var sessionList=data.session_list.session;
                           for(var i=0;i<sessionList.length;i++){
                           	var conv = sessionList[i];
                           	var msguncount=parseInt(conv.message.msguncount)
                               if(conv){
                                   unread += msguncount;
                               }
                           	if(conv.reqtimes == "0"){
                           		hasNewConv = true;
                            }
                               //console.log(unread);
                               
                           }
                           
                           if(unread > 0) {
                               if(msgCount<unread){
                                   $("#tipsAudio").get(0).play();
                               }
                               msgCount=unread;
                               if(!titleTimer) {
                                   titleTimer = setInterval(function(){
                                       if(count%2 == 0) {
                                           document.title ="★您有新消息★-"+ title ;
                                       } else {
                                           document.title = title;
                                       }
                                       count++;
                                   }, 1000);
                               }
                           }
                           
                           if(unread > 0) {
                               $("#chatcorner").css("display", "block");
                               //$("#chatcorner").text(unread);
                           } else if(titleTimer) {
                        	   clearInterval(titleTimer);
               				   titleTimer = null;
                           }
						   if(hasNewConv){
							   ImccPlugin.msgTip(tooltipid, "0", ""+data.session_list.count, ""+unread, "您有一通新会话", title);
                           } else if(unread > 0) {
                        	   ImccPlugin.msgTip(tooltipid, "0", ""+data.session_list.count, ""+unread, "您有"+unread+"条未读消息", title);
                           } else {
                        	   ImccPlugin.msgTip(tooltipid, "0", ""+data.session_list.count, "0", "0", title);
                           }
                       } else {
                           $("#chatcorner").css("display", "none");
                           ImccPlugin.msgTip(tooltipid, "0", "0", "0", "0", title);
                       }
                       // 电话客服且客服偏好2：如果IM达到最大接入量，则电话示忙
                       if(''=="Y" && '' == '2'){
                            var defaultPhoneMaxcount = '';
                            if(!defaultPhoneMaxcount || data.session_list.count >= parseInt(defaultPhoneMaxcount)){
                                isPhoneChange = true;
                                busy(1);
                            }else{
                                if(isPhoneChange){ //true自动切换模式
                                    busy(0); //切回在线
                                    isPhoneChange = false; //false手动切换模式
                                }
                            }
                       }
                       
                    }else if(data.code==1) {
                        //重新登录
                        cLogin();
                     }
		        	 
		        },
		        error : function(jqXHR, textStatus, errorThrown){
		        },
		        complete: function(){}
			});
		}
	}
	
	if(true){
 		convlist();
 		convTimer = setInterval(convlist, 5000);
    }
	
    //左侧菜单鼠标点击电话，电话变动态
    $('.icon-phone-square').on('click',function(){
     $(this).addClass("tada");
    }).on('mouseout',function(){
      $(this).removeClass("tada");
    });
   //顶部电话鼠标移入变动态
    $('.icon-dianhua').on('mouseover',function(){
//       $(this).css('background-image','url(../static/assets/img/dianhua2.gif)');
    })
    $('.icon-dianhua').on('mouseout',function(){
//       $(this).css('background-image','url(../static/assets/img/zaixian.png)');
    });
});

function test(){
	$.ajax({
					type : "POST",
					url : "/phone/onRecordReadIn.do",
					data : {
						"ani" : "86954601"
					},
					async : false,
					cache : false,
					success : function(data) {
						if(data.isService == "true"){
							window.parent.treeReasonOpen(data.sessionid,data.reasonId);
						}
					},
					error : function() {
						notify("提示", "插入呼入会话记录失败", "fail", 2000);
					}
				});
}

function cLogin(){
    var url = "/chat/logon.do";
    var headers = {};
    $.ajax({
        type: 'post', 
        headers: headers,
        url: url, 
        async: true, 
        dataType : 'json',
        success: function(data){
            
        },
        error : function(jqXHR, textStatus, errorThrown){
            
        },
        complete : function(){}
    });
}

function getMsgId(len){
    len = len || 32;
	var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
	var maxPos = $chars.length;
	var pwd = '';
	for (i = 0; i < len; i++) {
		   pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return pwd;
}

       	
/************************************电话相关begin****************************************/ 	
    //客服端登录方法
function OnLoginClickIMCC(agentid, password, ctiserver, devicename,
			autoWrapEndTime, state, SipIp) {
		// 		alert("AgenId: " + agentid + " | pas: " + password + "| ips: " + ctiserver + "| fj : " + devicename + "| times: " + autoWrapEndTime);
	agProxy.onLoginSucc = function() {
		busy(state);//登录成功后控制默认状态
		document.getElementById("callup").style.display='block';
	// 			window.JSRelogin();//登录成功后通知客服端
	// 			setInterval("window.JSHello()",2000);
	};
	
	agProxy.onLoginFail = function(reason) {
// 		alert('登录失败!' + reason);
		notify("提示", reason, "fail", 2000);
	};
	
	//只要电话来了都会运行这个函数
	agProxy.OnEvtCallArrive = function(ani, dnis) {
		//状态为通话IM自动示忙
		if(''=='0'){
			switchStatus('3');//IM示忙
			isPhoneChange = true;
		}
		document.getElementById("txtAni").innerHTML = ani;
		callType = 0;//设置呼叫类型
		Ani = "";//先置空来电号码
		AniTwo = "";
		Ani = ani;
		AniTwo = ani;
		$('.icon-phone-square').addClass("tada");
		dict = agProxy.DoGetAssociatedData("Location");//来电归属地
		window.parent.phone(ani,callType,dict);
		phoneHref();//超链接赋值
		Ani ="";
	};
	
	agProxy.OnEvtAnswerSucc = function() {//应答成功事件
	};
	
	agProxy.OnEvtAutoReturned = function() {};
	
	agProxy.OnEvtRecord = function(recordfilepath) {};
	//外拨成功事件
	agProxy.OnMakeCallSucc = function() {
		phoneHref();
// 		jishi();
		$("#callup").popover('hide');
		isCallOver = true;//拨通后电话取消呼叫状态开关
	};
	
	agProxy.OnMakeCallFailed = function(reason) {};
	agProxy.EvtCallCleared = function() {//挂机事件
// 		stopCount();//停止计时
		Ani= "";
		callType = 1;
		//呼出时在这里触发会话记录
// 		if(callType == 1){
// 			agProxy.Timereset();//将通话时间重置
// 		}
		phoneHref();//重置超链接
	};
	
	agProxy.OnZj = function() {//转接成功停止计时
		stopCount();
	};
	
	agProxy.Timereset = function() {//重置通话计时
		//接听电话结束进入第三方库取数据
		if(callType == 0){
			Ani= "";
			callType = "";
			phoneHref();//重置超链接
			window.parent.treeReasonOpen(AniTwo);//来话原因采集
			setTimeout(function(){
				window.parent.updateRecord();
			},7000);
			return;
			//这里写会话记录
			setTimeout(function() {
				$.ajax({
					type : "POST",
					url : "/phone/onHookHandle.do",
					data : {
						"ani" : AniTwo
					},
					async : false,
					cache : false,
					success : function(data) {
						window.parent.updateRecord();
						if(data.isService == "true"){
							window.parent.treeReasonOpen(data.sessionid,data.reasonId);
						}
					},
					error : function() {
						notify("提示", "插入呼入会话记录失败", "fail", 2000);
					}
				});
			}, 6000);
		}else if(callType == 1){//呼出
			if(Ani){
				AniTwo = Ani;
			}
			Ani= "";
			callType = "";
			phoneHref();//重置超链接
			window.parent.treeReasonOpen(AniTwo, 1);//来话原因采集不弹屏div
			setTimeout(function(){
				window.parent.updateRecord();
			},7000);
			if(taskCustomerId!=""){//如果是外呼任务呼出的电话，修改相关数据
				$.ajax({
                    type : "POST",
                    url : "/mycalltask/updateHangUp.do",
                    data : {
                        "taskCustomerId" : taskCustomerId
                    },
                    cache : false,
                    success : function(data) {

                    }
                });
			}
			taskCustomerId="";
			return;
			setTimeout(function() {
				$.ajax({
					type : "POST",
					url : "/phone/addCallRecord.do",
					data : {
						"ani" : AniTwo
					},
	// 				async : false,
					cache : false,
					success : function(data) {
						Ani= "";
						callType = "";
						phoneHref();//重置超链接
						window.parent.updateRecord();
					},
					error : function() {
						Ani= "";
						callType = "";
						phoneHref();//重置超链接
						notify("提示", "插入呼出会话记录失败", "fail", 2000);
					}
				});
			},6000);
		}
	};
	agProxy.DeviceName = devicename;
	agProxy.WSURI = "ws://" + ctiserver + ":5555";
	agProxy.AutoWrapEndTime = autoWrapEndTime;
	agProxy.StateInterpretor.m_AutoWrapEndTime = autoWrapEndTime;
	agProxy.SipIP = SipIp;
	
	//setTimeout(function () {
			agProxy.DoLogin(agentid, password);
	// }, 1300);
}

function phoneHref(){
	var bhref = "/phone/main.do?ani="+Ani+"&callType="+callType;
	$("#phoneHref").attr('url', bhref);
}

//设置客服端登录后默认状态
function busy(state) {
	var nowState = $("#state").text();
	if(nowState=="未登录状态") return;
	if (state == "1") {
		this.agProxy.CmdPause("01");//示忙
		stateText = "缺省";
		stateColour = "#F88B50";
		document.getElementById("online").innerHTML = stateText;
	    document.getElementById("online").style.background = stateColour;
	} else {
		this.agProxy.CmdContinue();//空闲
	}
}

//客服端登出方法
function OnLogOutClick() {
	agProxy.DoLogOut();
}

//电话页面所有按钮点击事件
function btn(obj) {
	this.agProxy.StateInterpretor.agUI.onButtonClick(obj);
}

//转接坐席ID赋值
function setAgentId(id){agentId = id;}

//确认转接
function selectOK() {
	//根据所选来进行处理
    if (!category) {
       	var phoneNum = document.getElementById("newAni").value;
        //选择的是转接外线
        if (phoneNum == "") {
//          	alert("请输入被转接的外线号码!");
         	notify("提示", "请输入被转接的外线号码", "info", 2000);
            return;
        }
        else {
        	//转接座席和转接外线号码其实用的是一个函数CmdTransferToAgent
            //只不过传递的参数不一样，转接外线的传递的参数，前面以$开头，这样就表示后面跟的是号码
            agProxy.CmdTransferToAgent("$" + callupPrefix + phoneNum);
        }
        $("#Transfer").popover('hide');//隐藏转接
    }
    else {
    	//选择的是转接座席
        if (agentId == "") {
//         	alert("请输入被转接的座席!");
        	notify("提示", "请输入被转接的座席!", "info", 2000);
            return;
        } else {
        	//转接座席和转接外线号码其实用的是一个函数CmdTransferToAgent
            //只不过传递的参数不一样，转接外线的传递的参数，前面以$开头，这样就表示后面跟的是号码
//                 var agentSel = combobox_agents.getValue();
            var iPos = agentId.indexOf('|');
            var sAgentID = agentId;
            if(agentId.indexOf('|') >= 0){
        		sAgentID = agentId.substring(0,iPos);
            }
            agProxy.CmdTransferToAgent(sAgentID);
                //agProxy.CmdTransferToAgent(combobox_agents.getValue());
        }
        agentId = "";
        $("#Transfer").popover('hide');
    }
}
    
  //转接取消
function passChatCancel(){
	this.agProxy.CmdTransferCancel();
	$("#Transfer").popover('hide');
}
    
//确认小休
function pauseSelectOK(id) {
    if (id == "") {
//         alert("请选择小休原因");
        notify("提示", "请选择小休原因!", "info", 2000);
    }
    else {
       this.agProxy.CmdPause(id);
    }
}  
     
//计时器
var timer;
function jishi() {
	var HH = 0;
	var mm = 0;
	var ss = 0;
	var str = '';
	timer = setInterval(function() {
		str = "";
		if (++ss == 60) {
			if (++mm == 60) {
				HH++;
				mm = 0;
			}
			ss = 0;
		}

		str += mm < 10 ? "0" + mm : mm;
		str += ":";
		str += ss < 10 ? "0" + ss : ss;
		document.getElementById("Time").innerHTML = str;
	}, 1000);
	
// 	alert("创建时："+timer);
}
    
//停止计时
function stopCount() {
// alert("结束时："+timer);
	setTimeout(function() {
		document.getElementById("txtAni").innerHTML = "";
		window.clearInterval(timer);
		timer = null;
		document.getElementById("Time").innerHTML = "";
	},200);
}
	
function isInside(obj){
	category = obj;
}

//外拨
function DialOutClick(id){
	this.agProxy.CmdPause(id);
	setTimeout('$(".jianpan").show()',300);
}




/**
电话外拨接口
*/
var resetautoCallOut;
var taskCanCall=1;
function callOut(phoneNum){
    if(!phoneNum){
        new PNotify({title: '通知', text: '外拨失败，请输入电话号码！', type: 'fail', delay: 2000});
        taskCanCall=9999;
        return false;   
    }
	var nowState = $("#state").text();
	if(nowState=="未登录状态"){
		new PNotify({title: '通知', text: '电话未登录状态', type: 'fail', delay: 2000});
		taskCanCall=9999;
		return;
	}
	if(nowState=="挂机中状态"){
		taskCanCall=9999;
		new PNotify({title: '通知', text: '电话正在挂机中，请稍后', type: 'fail', delay: 2000});
		resetOnLoginClickIMCC();
		return;
	}
	if(nowState=="外拨中状态"){
        taskCanCall=9999;
        new PNotify({title: '通知', text: '电话正在外拨中，请挂机后再试', type: 'fail', delay: 2000});
        return;
    }
	if(nowState!="示忙状态" && nowState!="话后状态"){
	    busy("1");
	    resetautoCallOut = setInterval(function(){
	    	var nowState = $("#state").text();
			if(nowState=="示忙状态"){
				DialOutClick("01");//打开键盘
				dialOutNum = phoneNum;//外拨号码赋值
				/**
					modify by baosheng 2016-10-13
					替换原有外拨方法，外拨新增主叫号码参数
				**/
				//this.agProxy.CmdDialOut(callupPrefix + phoneNum);
				new PNotify({title: '通知', text: '主叫号码是：'+v_ani, type: 'fail', delay: 1000});
				this.agProxy.CmdDialOutWithAni(callupPrefix + phoneNum,v_ani);
				
				document.getElementById("txtAni").innerHTML = phoneNum;
				
				isCallOver = true;
				window.parent.phone(dialOutNum,"1",null);
				Ani = dialOutNum;
				
				isCallOver = true;//取消按钮打开
				new PNotify({title: '通知', text: '外拨中，请等待...', type: 'fail', delay: 1000});
				clearInterval(resetautoCallOut);
			}
	    }, 1000);
	}else{
// 		pauseSelectOK('2');
// 		stateText = "回访";
// 		stateColour = "#F88B50";
		DialOutClick("01");//打开键盘
		dialOutNum = phoneNum;//外拨号码赋值
		/**
			modify by baosheng 2016-10-13
			替换原有外拨方法，外拨新增主叫号码参数
		**/
		//this.agProxy.CmdDialOut(callupPrefix + phoneNum);
		new PNotify({title: '通知', text: '主叫号码是：'+v_ani, type: 'fail', delay: 1000});
		this.agProxy.CmdDialOutWithAni(callupPrefix + phoneNum,v_ani);
		
		isCallOver = true;
		window.parent.phone(dialOutNum,"1",null);
		
		document.getElementById("txtAni").innerHTML = phoneNum;
		
		Ani = dialOutNum;
		
		isCallOver = true;//取消按钮打开
		new PNotify({title: '通知', text: '外拨中，请等待...', type: 'fail', delay: 1000});
	}
}
function getState(tcId,callback){
	taskCustomerId=tcId;
	callback(taskCanCall);
}


//电话重新登录方法
var resetTimer;
function resetOnLoginClickIMCC(){
    OnLogOutClick();
    setTimeout(function(){
		OnLoginClickIMCC('','','','','','','');
    },1000);
    
    if(dialOutNum!=""){
    	resetTimer = setInterval(resetIMCCTimer, 1000);
    }
}

function resetIMCCTimer(){
	busy("1");//先示忙
	var nowState = $("#state").text();
	if(nowState=="示忙状态" && nowState!="话后状态"){
		this.agProxy.CmdDialOutWithAni(callupPrefix + dialOutNum,v_ani);
		isCallOver = true;
		$("#DialOut").hide();
		$("#overCall").show();
		clearInterval(resetTimer);
	}
}

/**************************************电话相关end*******************************************/

/************************ 轮询最新的新会话 begin ******************************/
var MAX_PN_LEN = 5; //弹窗最大数
var POLLING_FLAG = true; //控制是否轮询
//关闭轮询
function closePolling(){
	POLLING_FLAG = false;	
}
//重启轮询
function restartPolling(){
	if(!POLLING_FLAG)
		updater.poll();
}
/************************  轮询最新的新会话 end ********************************/


var changeCountOpera = 1; //1表示点击减号或加号或直接修改接入量的时候可以访问后台。2表示不可以。(防止多次点击后台没有处理完数据出现数据混乱)

$(function(){
    //启动轮询
    //updater.poll();
    $('#status').val('1');
    var userId = '28504';
    getUserTypeName(userId);
    //$("input[name='online']").click(function(){
    //	switchStatus($(this).val());
   // });
    
    // 消息预览改变事件
    $("#previewMsg").change(function() {
    	if($(this).is(":checked")){ //表示开启预览
    		changePreviewNewMessage("1");
    	}else{ //表示关闭预览
    		changePreviewNewMessage("2");
    	}
    }); 
    
  $('#defaultConnCount').on('keyup', function() {
	  $(this).val($(this).val().match(/[1-9]\d*|[0]{1,1}/));
      if(event.keyCode == 13){
        if(this.value.trim().length == 0) return;
        if(changeCountOpera == 1){
        	changeCountOpera == 2;
        	changeConnCount(userId, this.value.trim());
        }
      }
   });
  
});


// 接入量加1或减1
function addOrSubtractConnCount(changeType){
	var userId = '28504';
	var count = $('#defaultConnCount').val();
	if(changeType == "subtract"){
		if(count != '' && count <= 0){
			notify("提示", "接入量已不能再减", "info", 2000);
			return;
		}
	}
	
	if(changeCountOpera == 1){
		changeCountOpera = 2;
		$.ajax({
	        url : '/user/addOrSubtractConnCount.do',
	        type : 'post',
	        data : {"userId":userId,"changeType":changeType},
	        dataType: 'json',
	        success : function(data){
	        	if(data.success){
	        		notify("提示", "修改接入量成功", "info", 2000);
	        		changeCountOpera = 1;
	        		$("#defaultConnCount").val(data.respText);
	        	}else{
	        		notify("提示", data.respText, "fail", 2000);
	        		changeCountOpera = 1;
	        	}
	        },
	        error: function (data){
	        	notify("提示", "修改接入量失败", "fail", 2000);
	        	changeCountOpera = 1;
	        }
	    });
	}
}

//直接修改接入量
function changeConnCount(userId, count){
		$.ajax({
	        url : '/user/changeConnCount.do',
	        type : 'post',
	        data : {"userId":userId,"count":count},
	        dataType: 'json',
	        success : function(data){
	        	if(data.success){
	        		notify("提示", "修改接入量成功", "info", 2000);
	        		changeCountOpera = 1;
	        	}else{
	        		notify("提示", data.respText, "fail", 2000);
	        		changeCountOpera = 1;
	        	}
	        },
	        error: function (data){
	        	notify("提示", "修改接入量失败", "fail", 2000);
	        	changeCountOpera = 1;
	        }
	    });
}

//获取用户的职位名称
function getUserTypeName(userId){
	$.ajax({
        url : '/user/getUserTypeName.do',
        type : 'post',
        data : 'userId=' + userId,
        dataType: 'json',
        success : function(data){
        	if(data.success){
        		$("#userType").text(data.respText);
        	}
        },
        error: function (data){
           
        }
    });
}

var oldStatus = '1';
function switchStatus(status){
	var url='/user/switchStatus.do';
	//var url ="";
    if(!status){
        status = $('#onlineSel').val();
    }
    $.ajax({
        url : url,
        type : 'post',
        timeout : 5000, //超时时间设置，单位毫秒
        data : 'status=' + status,
        dataType: 'json',
        success : function(data){
            if(!data){ return;}
            if('success' == data.msg){
                oldStatus = status;
                $("#onlineSel").val(oldStatus);
            } else {
                $("#onlineSel").val(oldStatus);
                notify("提示", data.msg, "fail", 2000);
            }
            //set login user status
		    var v = $("#onlineSel").find("option:selected").index();
		    $('#navbar i.zt').css("background" ,statusArr[v]);
        },
        error: function (data){
            $("#onlineSel").val(oldStatus);
            notify("提示", "切换状态失败！", "fail", 2000);
            //set login user status
		    var v = $("#onlineSel").find("option:selected").index();
		    $('#navbar i.zt').css("background" ,statusArr[v]);
        }
    });
}

function syncStatus(status) {
	var currstatus = $('#onlineSel').val();
	if(status && status != currstatus) {
		$('#onlineSel').val(status);
		var v = $("#onlineSel").find("option:selected").index();
	    $('#navbar i.zt').css("background" ,statusArr[v]);
	}
}

// 消息预览改变事件
function changePreviewNewMessage(previewNewMessage){
	$.ajax({
        url : '/user/changePreviewMsg.do',
        type : 'post',
        data : 'previewNewMessage=' + previewNewMessage,
        dataType: 'json',
        success : function(data){
        	 notify("提示", data.respText, "info", 2000);
        },
        error: function (data){
            notify("提示", "修改用户消息预览状态失败！", "fail", 2000);
        }
    });
}

//跳转到个人信息
function toLoginUser(){
	$('.ucc-main .main iframe').attr('src', "/loginUser/toLoginUser.do");
}
function toWorkerCount(){
    $('.ucc-main .main iframe').attr('src','/outside/menu/jump.do?redirectUrl=http://u.im-cc.com/ucc-api/static/html/staff/staff_count.html');
}
//消息通知
function notify(title, text, type, times){
    new PNotify({
        title: title,
        text: text,
        type: type,
        delay: times
    });
}

//统一添加消息通知
function addNews(id, html, dd_size) {
    var $node = $('#' + id);
    $node.append(html);
    //控制有无消息的提示绿点
    //控制有无消息的提示绿点
    var hasNews = $('#laterNews dd').length >0;
    var workOrders = $('#workOrders dd').length >0;
    var completionStatus = $('#ProcessingNotice dd').length >0;
    if(hasNews || workOrders || completionStatus){
        $('.icon-bell').addClass('in');
    }else{
        $('.icon-bell').removeClass('in');
    }
  }
   function getContactPlanNews() {
       //公司公告
     window.apiRequest({
      url: "noticeuser/search",
      type : 'get',
      data: {"count":"1","status":"2"},
      dataType : 'json',
      success : function(data){
        if(!data.page){return;}
        var html = '';
        var obj = {};
        if(data.page.items){
          if(data.page.items.length=="0"){
            return;
          }
          for(var i = 0; i < data.page.items.length; i++){
            obj = data.page.items[i];
            if(!obj){
              continue;
            }
            html += '<dd class="list-group-item" id="'+obj.id+'">';
            html += ' <span>【公司公告】</span>';
            html += ' <a class="limitlength" href="javascript:void(0);" id="affiche">'+obj.title+'</a>';
            html += '</dd>';
          }
          $("p.noMsg").hide();
          $(".newnote-container .footer-btns").show();
          addNews("laterNews",html,data.page.items.length)
        }
        else{
         return;
       }
     },
     error : function(data){}
   });
   //工单提醒
    $.ajax({
      url: window.IMCC_CONTEXT_PATH +'workOrderMng/searchNotice.do',
      type : 'get',
      data: {"count":"1","pn":"1"},
      dataType : 'json',
      success : function(data){
        if(!data.page){return;}
        var html = '';
        var obj = {};
        if(data.page.items){
          if(data.page.items.length=="0"){
            return;
          }
          for(var i = 0; i < data.page.items.length; i++){
            obj = data.page.items[i];
            if(!obj){
              continue;
            }
            html += '<dd class="list-group-item" id="'+obj.id+'">';
             html += ' <span>【工单提醒】</saan>';
            html += ' <a class="limitlength" href="javascript:void(0);" id="toWorkorder">'+obj.title+'</a>';
            html += '</dd>';
          }
          $("p.noMsg").hide();
          $(".newnote-container .footer-btns").show();
          addNews("workOrders",html,data.page.items.length)
        }
        else{
         return;
       }
     },
     error : function(data){}
   });
  //系统提醒
    $.ajax({
      url: window.IMCC_CONTEXT_PATH +'workOrderMng/searchProcessingNotice.do',
      type : 'get',
      data: {"count":"1","pn":"1"},
      dataType : 'json',
      success : function(data){
        if(!data.page){return;}
        var html = '';
        var obj = {};
        if(data.page.items){
          if(data.page.items.length=="0"){
            return;
          }
          for(var i = 0; i < data.page.items.length; i++){
            obj = data.page.items[i];
            if(!obj){
              continue;
            }
            html += '<dd class="list-group-item" id="'+obj.woId+'">';
             html += ' <span>【系统提醒】</saan>';
            html += ' <a class="limitlength" href="javascript:void(0);" id="toProcessingNotice">'+obj.content+'</a>';
            html += '</dd>';
          }
          $("p.noMsg").hide();
          $(".newnote-container .footer-btns").show();
          addNews("ProcessingNotice",html,data.page.items.length)
        }
        else{
         return;
       }
     },
     error : function(data){}
   });
  }
  function showRedSign() {
    $.ajax({
      url: window.IMCC_CONTEXT_PATH + 'home/getStatisticLeaveWord.do',
      type: 'post',
      dataType: 'json',
      success: function (data) {
        if (data.isSuccess && data.count > 0) {
          $("#chatcorner2").css("display", "block");
        } else {
          $("#chatcorner2").css("display", "none");
        }
      },
      error: function (data) {
        $span.html(0).hide();
      },
      complete: function () {
      }
    });
    $.ajax({
      url: window.IMCC_CONTEXT_PATH + 'home/getStatisticNoAssLeaveWord.do',
      type: 'post',
      dataType: 'json',
      success: function (data) {
        if (data.isSuccess && data.count > 0) {
          $("#chatcorner3").css("display", "block");
        } else {
          $("#chatcorner3").css("display", "none");
        }
      },
      error: function (data) {
        $span.html(0).hide();
      },
      complete: function () {
      }
    });
  }
  var newsTimer = setInterval(pullNews, 1 * 60 * 1000);//时间可与计数器配合自由组合
  //-------------消息提醒定时器 end-----------------
  
  function getHyxCookie (name) {
      var arg = name + "=";
      var alen = arg.length;
      var clen = document.cookie.length;
      var i = 0;
      var j = 0;
      var cookieStr = document.cookie;
      while (i < clen) {
          j = i + alen;
          if (document.cookie.substring(i, j) == arg) {
              var endstr = cookieStr.indexOf(";", j);
              if (endstr == -1) endstr = cookieStr.length;
              return unescape(cookieStr.substring(j, endstr));

          }
          i = document.cookie.indexOf(" ", i) + 1;
          if (i == 0)
              break;
      }
      return "";
  }
  
  //调用api接口
  window.apiRequest = function(ajaxoptions) {
	  var hosttel = getHyxCookie("hosttel") || "";
	  var alg = getHyxCookie("alg") || "";
	  var token = getHyxCookie("token") || "";
	  if(ajaxoptions.url.indexOf("?") < 0) {
        ajaxoptions.url = window.IMCC_API_PATH + ajaxoptions.url+"?token="+token+"&hosttel="+hosttel+"&alg="+alg;
      } else {
        ajaxoptions.url = window.IMCC_API_PATH + ajaxoptions.url+"&token="+token+"&hosttel="+hosttel+"&alg="+alg;
      }
	  $.ajax(ajaxoptions);
  }

  window.api = {
     callout: function(hostNumber, imType, openid, callback){
       if(!hostNumber && callback && (typeof callback == "function")){
         callback({code:10, reason:"外呼失败，请选择主号"});
         return;
       } else if(!imType && callback && (typeof callback == "function")){
         callback({code:10, reason:"外呼失败，请选择IM类型"});
         return;
       } else if(!openid && callback && (typeof callback == "function")){
         callback({code:10, reason:"外呼失败，请输入IM号码"});
         return;
       }
       var type = "0";
       var url = window.IMCC_CONTEXT_PATH + "chat/callOut.do";
       var headers = {};
       $.ajax({
         type: 'post',
         headers: headers,
         url: url,
         async: true,
         dataType : 'json',
         data: {
           hostNumber: hostNumber,
           imType: imType,
           openid: openid,
           type: type
         },
         success: function(data){
           if (data.code == 0) {
             if(callback && (typeof callback == "function")){
               callback({code:0, reason:""});	
             }
             setTimeout(function(){
               window.chooseFirstMenu("会话", true);
             }, 500);
           } else {
             var text = "外呼失败";
             if(data.code == 100) {
               text = "非好友用户，外呼失败！";
             } else if(data.code == 200) {
               text = "无QQ外呼权限，外呼失败";
             }
             if(data.reason){
           	   if(callback && (typeof callback == "function")){
                 callback({code: data.code, reason: data.reason});
           	   }
             }else{
           	   if(callback && (typeof callback == "function")){
           	     callback({code:11, reason:text});
           	   }
             }
           }
         },
         error : function(jqXHR, textStatus, errorThrown){
       	  if(callback && (typeof callback == "function")){
       	    callback({code:999, reason:"外呼失败,网络请求失败"});
       	  }
         }
       });
     }
  };

  window.onmessage = function(event) {
	  if(event.data.command == "api.callout") {
		  window.api.callout(event.data.hostNumber, event.data.imType, event.data.openid, function(res){
			  res.command = "api.callout",
			  event.source.postMessage(res, event.origin);
		  });
	  }
  }
  
  function signout() {
	//if(confirm("是否确认登出？")) {
		if(convTimer) {
			clearInterval(convTimer);
		}
		$.ajax({
 	        type : 'GET',
 	        url : '/loginOut.do',
 	        success : function(data) {
              	if (data.success) {		//请求提交成功
              		document.location.href='/index.jsp';
              	}else {
      				alert("请求提交失败," + data.respText);
      			}
 		    },
 		    error : function(data) {
 		    	document.location.href='/index.jsp';
 		    }
 	    });
}
/****** websocket 强制登录  start add by  huangbs 2016-05-18************/
//生产环境
var ws = new WebSocket("ws://u.im-cc.com:17999/wsServlet");
  //测试环境
//var ws = new WebSocket("ws://192.168.10.37:8085/wsServlet");
var ran_num = getHyxCookie("ran_num") || "";
console.log(ran_num);
var user_ran_num = '1000@11578' + "##" + ran_num;

var heartCheck = {
    timeout: 5000,//5s
    timeoutObj: null,
    serverTimeoutObj: null,
    reset: function(){
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
　　　　 this.start();
    },
    start: function(){
        var self = this;
        this.timeoutObj = setTimeout(function(){
            ws.send(user_ran_num);
            self.serverTimeoutObj = setTimeout(function(){
                //ws.close();//如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
				reconnect();
            }, self.timeout)
        }, this.timeout)
    },
}

ws.onopen = function(){
	ws.send(user_ran_num);
	heartCheck.start();
};

ws.onmessage = function(message){
	if(message.data=="offline")
	{
		new PNotify({
            title: '通知',
            text: '该账号已在其他地方登录，您已被迫下线！',
            type: 'fail',
            delay: 3000
        });
        setTimeout(signout,4000);
	}
	else
	{
		heartCheck.reset();
	}
};

ws.onclose = function () {
    reconnect();
};
ws.onerror = function () {
    reconnect();
}
 
 
/****** wsocket 强制登录  end ************/  
  
  function pullNews() {
      $(".newnote-container dd").remove();
      getContactPlanNews();
      showRedSign();
  }
	//新手指引
	function toNoviceGuide(){
	  // 页面加载完成显示新手引导
      $('#modalIntro').modal('show');
      return $(".sm-mask").click();
	}
	 jQuery(document).ready(function($) {
	 	var isGuide = 'Y';
	 	if(isGuide == "Y"){
	 		$('#modalIntro').modal('show');
	 	}
	    // 新手引导跳转页面
	    $('.intro-way a').on('click', function(event) {
	    	$('#modalIntro').modal('hide');
	        event.preventDefault();
	        var src = $(this).data('href');
	       	var name = $(this).text();
	        if(src == ""){
	        	notify("提示", "该功能完善中，请敬请期待！", "info", 2000);
	        	return;
	        }
	        chooseFirstAndSecondMenu('设置',name,true,'isGuide=Y');
	      });
	  });

 //状态提示：显示图片
var statusArr=["url('/static/assets/img/online.png') no-repeat center", 
        "url('/static/assets/img/busy.png') no-repeat center",
        "url('/static/assets/img/leave.png') no-repeat center"];
//ready
$(function(){
	$('#newNote').on('shown.bs.popover', function () {
              //公司公告
    $("#affiche").on("click",function(){
      $("#modalNotice").modal("show");
    })
    $("#toCompany").on("click",function(){
     chooseFirstAndSecondMenu('运营', '公司公告', true);
     $('#newNote').popover('hide');
     $("#modalNotice").modal("hide");
     $(".newnote-container dl#laterNews dd").remove();
     var hasNoticelist = $('.newnote-container dd').length >0;
     if(!hasNoticelist){
       $("p.noMsg").show();
       $(".newnote-container .footer-btns").hide();
       $("#newNote i.icon-bell").removeClass("in");
     }
   })
    //工单提醒
    $("#toWorkorder").on("click",function(){
      $("#modalOrder").modal("show");
    })
    $("#toOrder").on("click",function(){
      var orderId=$("#workOrders dd").attr("id");
      $.ajax({
        url:window.IMCC_CONTEXT_PATH+"workOrderMng/editRead.do",
        type:"get",
        data:{"id":orderId,"isRead":"1"},
        dataType:'json',
        success : function(data){
        },
        error : function(data){}
      });
      chooseFirstAndSecondMenu('待办', '我处理中的工单', true);
      $('#newNote').popover('hide');
      $("#modalOrder").modal("hide");
      $(".newnote-container dl#workOrders dd").remove();
      var hasNewslist = $('.newnote-container dd').length >0;
      if(!hasNewslist){
       $("p.noMsg").show();
       $(".newnote-container .footer-btns").hide();
       $("#newNote i.icon-bell").removeClass("in");
     }
   })
    //系统提醒
    $("#toProcessingNotice").on("click",function(){
      $("#modalSystem").modal("show");
    })
    $("#toOrderstatus").on("click",function(){
      var statusId=$("#ProcessingNotice dd").attr("id");
      $.ajax({
        url:window.IMCC_CONTEXT_PATH+"workOrderMng/editProcessingRead.do",
        type:"get",
        data:{"woId":statusId,"isRead":"1"},
        dataType:'json',
        success : function(data){
        },
        error : function(data){}
      });
      chooseFirstAndSecondMenu('待办', '我发起的工单', true);
      $('#newNote').popover('hide');
      $("#modalSystem").modal("hide");
      $(".newnote-container dl#ProcessingNotice dd").remove();
      var hasNewslist = $('.newnote-container dd').length >0;
      if(!hasNewslist){
       $("p.noMsg").show();
       $(".newnote-container .footer-btns").hide();
       $("#newNote i.icon-bell").removeClass("in");
     }
   })
    //全部已读
    $("button.readAll").on("click",function(){
      var woId=$("#workOrders dd").attr("id");
      var arg=$("#laterNews dd").attr("id");
      window.apiRequest({
        url:"noticeuser/editStatus",
        type:"post",
        data:JSON.stringify({"id":arg,"status":"1"}),
        dataType:'json',
        success : function(data){
          $("#laterNews dd#"+arg).remove();
        },
        error : function(data){}
      });
      $.ajax({
        url:window.IMCC_CONTEXT_PATH+"workOrderMng/editRead.do",
        type:"get",
        data:{"id":woId,"isRead":"1"},
        dataType:'json',
        success : function(data){
          $("#workOrders dd#"+woId).remove();
        },
        error : function(data){}
      });
      $(".newnote-container dd").remove();
      $("#newNote i.icon-bell").removeClass("in");
      $("p.noMsg").show();
      $(".newnote-container .footer-btns").hide();
      
    }),
    //查看更多
     $("#toMore").on("click",function(){
         chooseFirstAndSecondMenu('运营', '公司公告', true)
      })
    })
    $(document).on('hide.bs.popover','#newNote', function () {
      // 关闭时获取popover内容
        $('.icon-bell').removeClass('in');
    });
    pullNews();
    //set login user status
    var v = $("#onlineSel").find("option[value='1']").index();
    $('#navbar i.zt').css("background" ,statusArr[v]);
});
function refreshPersonalInfo(img, userName, userId){
    if(img && $('#personalImg').attr('src') != img){
        $('#personalImg').attr('src', img);
    }
    if(userName && $('#userName').html() != userName){
        $('#userName').html(userName);
    }
    if(userId){
        getUserTypeName(userId);
    }
}
function refreshDefaultConnCount(defaultConnCount){
    var cur = $('#defaultConnCount').val();
    if(cur != defaultConnCount){
        $('#defaultConnCount').val(defaultConnCount);
    }
}

//建立WebSocket连接
function foundWebSocket(port){
	setTimeout(function(){
// 		alert("6666");
		var webport = port.toString();
		var socket = new WebSocket("ws://127.0.0.1:"+webport);
		if(socket.readyState == "1"){
	// 		alert("成功返回值："+socket.readyState);
		}else{
	// 		alert("失败返回值："+socket.readyState);
		}
		socket.onopen = function(){
			var jsonstr = '{"agentId":"'+'28504'+'","path":"'+'http://uccfile.im-cc.com/'+'","hostTel":"'+'11578'+'"}';
			socket.send(jsonstr);
		};
		socket.onmessage = function(message){
			var dataObj=eval("("+message.data+")");//转换为json对象 
			for(var key in dataObj){
				//跳转来电客户信息页面
				if(key == "phoneNum" && dataObj[key]!="" && dataObj["path"]==""){
					window.parent.uboxPhone(dataObj[key],"","");
				}
				//对方挂机6秒后隐藏当前通话列表
				if(key=="isRing" && dataObj[key]!="" && dataObj["isRing"]=="1"){
					window.parent.hangPhone();//隐藏通话列表
					Ani= "";
					phoneHref();//重置超链接
				}
				//通话结束后整理会话记录
				if(key == "path" && dataObj[key]!="" && dataObj["phoneNum"]!=""){
					if(dataObj[key]!=""){
						$.ajax({
					        type: 'post', 
					        url: '/phone/saveUboxConversation.do', 
					        data:{"message":message.data},
					        success: function(data){
					        	window.parent.hangPhone();//隐藏通话列表
					        	Ani= "";
								phoneHref();//重置超链接
					            if(data.isService == "true"){
									window.parent.treeReasonOpen(data.sessionid,data.reasonId);
								}
					        },
					        error : function(jqXHR, textStatus, errorThrown){
					            notify("提示", "插入呼入会话记录失败", "fail", 2000);
					        }
					    });
					}
				}
			}
		};
	},"5000");
}
</script>
	<main class="container-fluid ucc-main sidebar-hide">
<aside class="sidebar">
  <ul class="nav nav-sidebar">
    <li class="" title="首页"><a href="javascript:void(0)" url="/home/toMain.do" menuname="首页"><i class="icon icon-home"></i> 首页</a><div class="ripple-container"></div></li>
    <li title="电话" class=""><a href="javascript:void(0)" url="/phone/main.do" menuname="电话" id="phoneHref"><i class="icon icon-phone-square"></i><span class="dian" style="display:none;" id="diancorner"></span>电话</a><div class="ripple-container"></div></li>
    <li title="会话" class="active"><a href="javascript:void(0)" url="/chat_v4/main/chat.html" menuname="会话"><span id="comment-menu"><i class="icon icon-comments"></i><span class="dian" id="chatcorner" style="display:none;"></span>会话</span></a><div class="ripple-container"></div></li>
    <li title="客户" class=""><a href="javascript:void(0)" url="/customer/base/toMain.do" menuname="客户"><i class="icon icon-kehu"></i> 客户</a><div class="ripple-container"></div></li>
    <li title="待办" class=""><a href="javascript:void(0)" url="/home/toNextMenus.do?page=待办" menuname="待办"><i class="icon icon-list-alt"></i><span class="dian" id="chatcorner2" style="display:none;"></span> 待办</a><div class="ripple-container"></div></li>
    <li title="统计" class=""><a href="javascript:void(0)" url="/home/toNextMenus.do?page=统计" menuname="统计"><i class="icon icon-tongji"></i> 统计</a><div class="ripple-container"></div></li>
    <li title="运营" class=""><a href="javascript:void(0)" url="/home/toNextMenus.do?page=运营" menuname="运营"><i class="icon icon-jiankong"></i><span class="dian" id="chatcorner3" style="display:none;"></span> 运营</a><div class="ripple-container"></div></li>
  </ul>
  <ul class="nav nav-sidebar nav-bottom">
    <li title="设置"><a href="javascript:void(0)" url="/home/toNextMenus.do?page=设置" menuname="设置"><i class="icon icon-cog"></i> 设置</a></li>
<!--     <li title="帮助"><a href="#帮助" url="" menuName="帮助"><i class="icon icon-question-circle"></i> 帮助</a></li> -->
  </ul>
</aside>    
<script>
/**
控制一级菜单
menuName : 菜单名称
isJump : 是否跳转，true || false
*/
function chooseFirstMenu(menuName, isJump){
    if(!menuName){ return;}
    $('.sidebar .nav-sidebar li').removeClass('active');
    var $choose = $('.sidebar .nav-sidebar li:has(a[menuName="' + menuName + '"])');
    $choose.addClass('active');
    if(isJump){
        $choose.find('a').click();
    }
}
/**
控制二级菜单
menuName : 菜单名称
isJump : 是否跳转，true || false
args : 菜单链接额外带的参数，单次跳转时有效，形如：aa=12&bb=123
*/
var chooseSecondMenuTimer = null;
function chooseSecondMenu(secondMenuName, isJump, args){
    var iframeName = 'mainFrame'; //iframe name attribute, and the id attribute is same value
    var finish = false;
    finish =  frames[iframeName].chooseSecondMenu(secondMenuName, isJump, args);
    if(chooseSecondMenuTimer && finish){
        clearInterval(chooseSecondMenuTimer);
        chooseSecondMenuTimer = null;
    }
    //操作执行完成后，要取消iframe的onload事件
    if(finish){
    	var iframe = document.getElementById(iframeName); //must id
		if (iframe.attachEvent){   //IE
		   iframe.attachEvent("onload", function(){}); 
		} else {
		   iframe.onload = function(){}; 
		}
    }
    return finish;
}

/**
同时控制一级菜单和二级菜单
firstMenuName : 一级菜单名称
secondMenuName : 二级菜单名称
isJump : 是否跳转，true || false
args : 菜单链接额外带的参数，单次跳转时有效，形如：aa=12&bb=123
*/
function chooseFirstAndSecondMenu(firstMenuName, secondMenuName, isJump, args){
    chooseFirstMenu(firstMenuName, true);
    var iframeName = 'mainFrame'; //iframe id attribute
    var iframe = document.getElementById(iframeName); //must id
    var itvlTime = 20;
	if (iframe.attachEvent){   //IE
	   iframe.attachEvent("onload", function(){
	       if(!chooseSecondMenu(secondMenuName, isJump, args))
           		chooseSecondMenuTimer = setInterval('chooseSecondMenu(\'' + secondMenuName + '\', ' + isJump + ', \'' + args + '\')', itvlTime);
	   }); 
	} else {
	   iframe.onload = function(){
	   		if(!chooseSecondMenu(secondMenuName, isJump, args))
	       		chooseSecondMenuTimer = setInterval('chooseSecondMenu(\'' + secondMenuName + '\', ' + isJump + ', \'' + args + '\')', itvlTime);
	   }; 
	}
}
</script>
		<div class="main">
      		<iframe name="mainFrame" id="mainFrame" src="./gzt_files/chat.html" frameborder="0" scrolling="yes"></iframe>
    	</div>
  	</main>
  	 <!-- 新手引导内容 -->
	  <div class="modal fade" id="modalIntro" role="dialog" aria-hidden="true" style="display: none;">
	    <div class="modal-dialog">
	      <div class="modal-content">
	        <div class="modal-header">
	          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
	        </div>
	        <div class="modal-body">
	          <h1>欢迎使用云软云客服平台！</h1>
	          <p>配置您的客户服务渠道，开始全新的客服体验。</p>
	          <nav class="intro-way">
	            <a data-href="/channel/phone/phoneList.do"><img src="./gzt_files/icon_call.png" alt="电话">电话</a>
	            <a data-href="/channel/weixin/wechatList.do?isGuide=Y"><img src="./gzt_files/icon_wx.png" alt="微信">微信</a>
	            <a data-href="/channel/tencent/qqList.do?isGuide=Y"><img src="./gzt_files/icon_qq.png" alt="QQ">QQ</a>
	            <a data-href="/channel/webchat/webchatList.do"><img src="./gzt_files/icon_webchat.png" alt="webchat">webchat</a>
<!-- 	            <a data-href=""><img src="/static/assets/img/zhifubao.png" alt="支付宝">支付宝</a> -->
	          </nav>
	        </div>
	      </div>
	    </div>
	  </div>
	
<script src="./gzt_files/common.js(1).下载"></script>
 <script src="./gzt_files/iscroll.js.下载"></script>
 <!-- jquery validation plugin -->
 <script src="./gzt_files/jquery.validate.min.js.下载"></script>
 <script src="./gzt_files/messages_zh.js.下载"></script>
 <script src="./gzt_files/layer.js.下载"></script>
 <script src="./gzt_files/pnotify.js.下载"></script>
 <script src="./gzt_files/pnotify.buttons.js.下载"></script>
 <script src="./gzt_files/webuploader.min.js.下载"></script>
 <!-- Select2 -->
<script src="./gzt_files/select2.full.min.js.下载"></script>
<!-- DataTables -->
<script src="./gzt_files/jquery.dataTables.min.js.下载"></script>
<script src="./gzt_files/dataTables.bootstrap.min.js.下载"></script>
<!-- bootstrap table -->
<script src="./gzt_files/bootstrap-table.min.js.下载"></script>
<script src="./gzt_files/bootstrap-table-zh-CN.min.js.下载"></script>
<script src="./gzt_files/msgBox.js.下载"></script>
<script src="./gzt_files/init.js.下载"></script>
</body></html>